// 等待DOM加载完成
window.addEventListener('DOMContentLoaded', function() {
    // 查找所有具有data-can-generate属性的URL输入框
    const urlInputs = document.querySelectorAll('input[data-can-generate="true"]');
    
    urlInputs.forEach(input => {
        // 获取父元素
        const parentElement = input.parentElement;
        
        // 创建生成URL按钮
        const generateButton = document.createElement('button');
        generateButton.type = 'button';
        generateButton.className = 'button-small';
        generateButton.style.marginLeft = '10px';
        generateButton.textContent = '生成URL';
        
        // 添加点击事件
        generateButton.addEventListener('click', function() {
            // 生成唯一的webhook ID
            const generateShortUuid = function() {
                return 'xxxxxxxxxxxx'.replace(/[x]/g, function(c) {
                    const r = Math.random() * 16 | 0;
                    return r.toString(16);
                });
            };
            
            // 获取项目信息
            const projectSelect = document.querySelector('select[name="project"]');
            let projectName = 'example-project';
            
            if (projectSelect && projectSelect.value) {
                // 从选项文本中提取项目名称
                const selectedOption = projectSelect.options[projectSelect.selectedIndex];
                projectName = selectedOption.text;
                
                // 处理项目名称，转换为slug格式
                projectName = projectName.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').substring(0, 20);
            }
            
            // 从当前页面URL获取域名和协议
            const baseUrl = window.location.origin;
            const webhookId = generateShortUuid();
            const newUrl = `${baseUrl}/webhooks/${projectName}/${webhookId}/receive`;
            
            // 更新输入框的值
            input.value = newUrl;
            
            // 添加一个简单的动画效果，提示URL已更新
            input.style.backgroundColor = '#e6f7ff';
            setTimeout(function() {
                input.style.backgroundColor = '';
            }, 1000);
        });
        
        // 将按钮添加到输入框旁边
        parentElement.appendChild(generateButton);
    });
});